<template>
    <div>
        <input type="file" @change="handleFileUpload" />
        <audio v-if="audioURL" :src="audioURL" controls></audio>
        <div>
            <p v-for="(item, index) in translations" :key="index">
                译文：<strong>{{ item.text }}</strong>
                <br>
                原文：<strong>{{ item.original }}</strong>
            </p>
            <button @click="startStreaming">开始识别</button>
            <button @click="endStream">停止识别</button>
        </div>
    </div>
</template>

<script>
// import WebSocket from 'ws'; // 注意：前端通常使用浏览器内置的WebSocket API，而不是ws库
import { v4 as uuidv4 } from 'uuid'; // 用于生成UUID

export default {
    name: "aiTranslate",
    data() {
        return {
            ws: null,
            taskStarted: false,
            audioFile: null,
            audioURL: '',
            translations: [],
            TASK_ID: uuidv4().replace(/-/g, '').slice(0, 32),
            sessionId: uuidv4().replace(/-/g, '').slice(0, 32),
        };
    },
    methods: {
        handleFileUpload(event) {
            const file = event.target.files[0];
            if (file) {
                this.audioFile = file;
                this.audioURL = URL.createObjectURL(file);
            }
        },
        initWebSocket() {
            const url = 'ws://192.168.120.8:8878/'+this.sessionId;

            this.ws = new WebSocket(url);

            this.ws.onopen = () => {
                console.log('连接到服务器');
                this.sendRunTask();
            };

            this.ws.onmessage = (event) => {
                const message = JSON.parse(event.data);
                switch (message.header.event) {
                    case 'task-started':
                        console.log('任务开始');
                        this.taskStarted = true;
                        this.sendAudioStream();
                        break;
                    case 'result-generated':
                        console.log('服务器返回结果：');
                        if (message.payload.output.translations) {
                            this.translations = message.payload.output.translations.map(trans => ({
                                text: trans.text,
                                original: trans.original || ''
                            }));
                        }
                        break;
                    case 'task-finished':
                        console.log('任务完成');
                        this.ws.close();
                        break;
                    case 'task-failed':
                        console.error('任务失败：', message.header.error_message);
                        this.ws.close();
                        break;
                    default:
                        console.log('未知事件：', message.header.event);
                }
            };

            this.ws.onclose = () => {
                if (!this.taskStarted) {
                    console.error('任务未启动，关闭连接');
                }
            };

            this.ws.onerror = (error) => {
                console.error('WebSocket错误：', error);
            };
        },
        sendRunTask() {
            const runTaskMessage = {
                header: {
                    action: 'run-task',
                    task_id: this.TASK_ID,
                    streaming: 'duplex'
                },
                payload: {
                    task_group: 'audio',
                    task: 'asr',
                    function: 'recognition',
                    model: 'gummy-realtime-v1',
                    parameters: {
                        sample_rate: 16000,
                        format: 'wav',
                        transcription_enabled: true,
                        translation_enabled: true,
                        translation_target_languages: ['en']
                    },
                    input: {}
                }
            };
            this.ws.send(JSON.stringify(runTaskMessage));
        },
        sendAudioStream() {
            const reader = new FileReader();
            reader.onload = (event) => {
                const arrayBuffer = event.target.result;
                this.ws.send(arrayBuffer);
                this.sendFinishTask();
            };
            reader.readAsArrayBuffer(this.audioFile);
        },
        sendFinishTask() {
            const finishTaskMessage = {
                header: {
                    action: 'finish-task',
                    task_id: this.TASK_ID,
                    streaming: 'duplex'
                },
                payload: {
                    input: {}
                }
            };
            this.ws.send(JSON.stringify(finishTaskMessage));
        },
        startStreaming() {
            if (this.audioFile) {
                this.initWebSocket();
            } else {
                alert('请先上传音频文件');
            }
        },
        endStream() {
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                this.ws.close();
            }
        }
    }
};
</script>

<style scoped>
/* 添加必要的样式 */
</style>